package com.fanqi.ipcapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import java.util.List;

//同一个app，activity和service跨进程的通信
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "AIDL";

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功后，将Binder对象转成AIDL接口
            IBookManager bookManager = IBookManager.Stub.asInterface(service);
            try {
                Book book1 = new Book("no12123223", "Java入门到放弃");
                Book book2 = new Book("no4545454665", "Android入门到放弃");
                bookManager.addBook(book1);
                bookManager.addBook(book2);
                List<Book> bookList = bookManager.getBooks();
                for (int i = 0; i < bookList.size(); i++) {
                    Log.d(TAG, "onServiceConnected: book" + i + bookList.get(i).getNo() + " name=" + bookList.get(i).getName());
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(this, MyService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }
}
